import axios from 'axios'
import qs from 'qs'
import common from './common'

const addTimestampToUrl = config => {
    // url添加参数
    let url = config.url, params = config.params, method = config.method,
        api = window.localStorage.getItem('ajaxApi') || '/_api'
    url = api + url // 使用'/_api'识别接口请求
    // if (process.env.NODE_ENV !== 'production' && url.indexOf('http') < 0) url = '/_api' + url // 开发环境使用'/_api'识别代理
    if (method === 'get' && params && Object.keys(params).length > 0) {
        // get请求统一将params序列化
        url = appendParams(url, qs.stringify(params))
        config.params = {}
    }
    // url请求加上时间戳
    config.url = appendParams(url, '_t=' + new Date().getTime())
    if (common.getUrlParam('token_enc')) config.url = appendParams(url, 'token_enc=' + encodeURI(common.getUrlParam('token_enc')))

    function appendParams(url, params) {
        if (url.indexOf('?') >= 0) {
            return url + '&' + params
        } else {
            return url + '?' + params
        }
    }

    return config
}, get = (url, params, config) => {
    return axios.get(url, {
        params
    }, config)
}, post = (url, data, config) => {
    return axios.post(url, data, config)
}

// 添加一个请求拦截器
axios.interceptors.request.use(function (config) {
    return addTimestampToUrl(config)
}, function (error) {
    return Promise.reject(error)
})

// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
    if (response.headers.redirect) {
        let redirect = response.headers.redirect,
            url = ((response.config.url.indexOf('logout') > -1) ? encodeURI(location.origin) : encodeURI(location.href))
        url = common.delUrlParam(url, 'token_enc')
        window.location.href = encodeURI(common.changeUrlArg(redirect, 'targetUrl', url))
    } else if (response.headers.dcsbstatus) {
        let url = encodeURI(location.origin)
        window.location.href = encodeURI(url + '/login')
    } else {
        if (response.config.url.indexOf('allResponse') > -1) {
            return response
        } else {
            if (!response.data.success && response.data.message && response.config.url.indexOf('noAlert') < 1) {
                common.messageBox('alert', response.data.message)
            }
            return response.data
        }
    }
}, function (error) {
    // 错误拦截
    if (error.response.data.message) {
        common.messageBox('alert', error.response.data.message)
    }
    common.updateView()
    return Promise.reject(error)
})

export default {
    get,
    post
}
